<script setup>
import { ref, onMounted, onUpdated, nextTick } from "vue";
import { getHistory, chat } from "./requests";
const messages = ref([
  // {
  //   id: 1,
  //   sender: "user",
  //   content: "你好，我有一个关于产品功能的问题",
  // },
  // {
  //   id: 2,
  //   sender: "assistant",
  //   content: "您好！很高兴为您服务。请问有什么可以帮助您的？",
  // },
  // {
  //   id: 3,
  //   sender: "user",
  //   content: "我想了解一下新版本的主要更新内容",
  // },
  // {
  //   id: 4,
  //   sender: "assistant",
  //   content:
  //     "新版本主要更新了以下功能：\n1. 优化了用户界面\n2. 添加了深色模式\n3. 提升了系统性能\n4. 新增了更多自定义选项",
  // },
]);

const chatList = ref([
  { id: "new", title: "新建对话", lastMessage: "点击开始新对话", isNew: true },
  { id: 1, title: "聊天 1", lastMessage: "这是最后一条消息" },
  // { id: 2, title: "聊天 2", lastMessage: "这是另一条消息" },
  // { id: 3, title: "产品讨论组", lastMessage: "下周一开会讨论新功能" },
  // { id: 4, title: "技术支持", lastMessage: "问题已解决，感谢反馈" },
  // { id: 5, title: "项目进度", lastMessage: "Sprint 3已完成90%" },
  // { id: 6, title: "团队公告", lastMessage: "请查看最新的开发文档" },
  // { id: 7, title: "Bug反馈", lastMessage: "已修复登录页面的问题" },
  // { id: 8, title: "需求收集", lastMessage: "新增了三个功能建议" },
]);

const userInfo = {
  avatar: "https://api.dicebear.com/7.x/avataaars/svg?seed=Felix",
  nickname: "测试用户",
  email: "test@example.com",
};

const currentChat = ref(null);
const isSidebarCollapsed = ref(false);
const inputMessage = ref("");
const typingMessage = ref("");
const isTyping = ref(false);
const messageContainer = ref(null);
const isLoading = ref(false);
const showScrollButton = ref(false);

const scrollToBottom = () => {
  if (messageContainer.value) {
    messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
  }
};

const handleScroll = () => {
  if (messageContainer.value) {
    const { scrollTop, scrollHeight, clientHeight } = messageContainer.value;
    showScrollButton.value = scrollHeight - scrollTop - clientHeight > 100;
  }
};

onMounted(() => {
  if (messageContainer.value) {
    messageContainer.value.addEventListener("scroll", handleScroll);
  }
  getHistory({ pageSize: 100, pageNum: 1 }).then((res) => {
    console.log(res, res.data);
    res.data.data.items.forEach((item) => {
      messages.value.push({
        id: item.id,
        sender: item.judge == 1 ? "user" : "assistant",
        content: item.message,
      });
    });
  });
});

const typeMessage = async (text) => {
  isTyping.value = true;
  typingMessage.value = "";
  for (let i = 0; i < text.length; i++) {
    typingMessage.value += text[i];
    if (text[i] === "\n" || i === text.length - 1) {
      await nextTick();
      scrollToBottom();
    }
    await new Promise((resolve) => setTimeout(resolve, 50));
  }
  isTyping.value = false;
  isLoading.value = false;
};

const createNewChat = () => {
  const newChat = {
    id: Date.now(),
    title: "新建对话",
    lastMessage: "等待开始对话",
    messages: [],
  };
  // 将新对话添加到列表中
  chatList.value = [
    chatList.value[0], // 保持新建对话按钮在最前
    newChat,
    ...chatList.value.slice(1),
  ];
  currentChat.value = newChat;
  messages.value = [];
};

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return;

  isLoading.value = true;
  const userMessage = {
    id: messages.value.length + 1,
    sender: "user",
    content: inputMessage.value,
  };
  messages.value.push(userMessage);
  const userInput = inputMessage.value;
  inputMessage.value = "";

  // 如果是新对话的第一条消息，更新对话标题
  if (currentChat.value && currentChat.value.title === "新建对话") {
    const newTitle =
      userInput.length > 20 ? userInput.slice(0, 20) + "..." : userInput;
    currentChat.value.title = newTitle;
    currentChat.value.lastMessage = userInput;
    // 更新chatList中的对话
    const chatIndex = chatList.value.findIndex(
      (chat) => chat.id === currentChat.value.id
    );
    if (chatIndex !== -1) {
      chatList.value[chatIndex] = currentChat.value;
    }
  }

  await nextTick();
  scrollToBottom();

  // 模拟AI助手的回复
  // const generateResponse = (input) => {
  //   const responses = {
  //     你好: "你好！很高兴为您服务。请问有什么可以帮助您的？",
  //     介绍: "我是一个AI助手，可以帮助回答问题、提供建议和解决问题。",
  //     再见: "再见！如果还有问题随时问我。",
  //     default: `我理解您的问题是关于"${input}"。让我为您详细解答：\n1. 这是一个很好的问题\n2. 我们可以从多个角度来分析\n3. 希望我的解答对您有帮助`,
  //   };

  //   for (const [key, value] of Object.entries(responses)) {
  //     if (input.includes(key)) return value;
  //   }
  //   return responses.default;
  // };

  // setTimeout(async () => {
  //   const response = generateResponse(userInput);
  //   const assistantMessage = {
  //     id: messages.value.length + 1,
  //     sender: "assistant",
  //     content: response,
  //   };
  //   messages.value.push(assistantMessage);
  //   await typeMessage(response);
  // }, 1000);
  chat({ question: userInput }).then((res) => {
    messages.value.push({
      id: messages.value.length + 1,
      sender: "assistant",
      content: res.data.data,
    });
  });

  setTimeout(async () => {
    await nextTick();
    scrollToBottom();
  }, 2000);

  isLoading.value = false;
};

const selectChat = (chat) => {
  if (chat.isNew) {
    createNewChat();
  } else {
    currentChat.value = chat;
  }
};

const toggleSidebar = () => {
  isSidebarCollapsed.value = !isSidebarCollapsed.value;
};
</script>

<template>
  <div class="chat-container">
    <div class="chat-list" :class="{ collapsed: isSidebarCollapsed }">
      <div class="collapse-button" @click="toggleSidebar">
        {{ isSidebarCollapsed ? ">" : "<" }}
      </div>
      <div class="chat-list-content">
        <div
          v-for="chat in chatList"
          :key="chat.id"
          class="chat-item"
          :class="{
            active: currentChat?.id === chat.id,
            'new-chat': chat.isNew,
          }"
          @click="selectChat(chat)"
        >
          <template v-if="chat.isNew">
            <h3>新建对话</h3>
            <p style="padding-left: 0">点击开始新对话</p>
          </template>
          <template v-else>
            <h3>{{ chat.title }}</h3>
            <p>{{ chat.lastMessage }}</p>
          </template>
        </div>
      </div>
      <div class="user-info">
        <img :src="userInfo.avatar" alt="用户头像" class="user-avatar" />
        <div class="user-details">
          <h3>{{ userInfo.nickname }}</h3>
          <p>{{ userInfo.email }}</p>
        </div>
      </div>
    </div>
    <div class="chat-main">
      <div class="chat-header">
        <h2>{{ currentChat ? currentChat.title : "请选择一个聊天" }}</h2>
      </div>
      <div class="chat-messages" ref="messageContainer">
        <button
          v-if="showScrollButton"
          @click="scrollToBottom"
          class="scroll-bottom-button"
        >
          ↓
        </button>
        <div
          v-for="message in messages"
          :key="message.id"
          class="message"
          :class="message.sender"
        >
          <img
            v-if="message.sender === 'assistant'"
            src="https://api.dicebear.com/7.x/bottts/svg?seed=Assistant"
            class="message-avatar"
            alt="AI头像"
          />
          <div class="message-content">
            <p>
              {{
                message.sender === "assistant" &&
                isTyping &&
                message === messages[messages.length - 1]
                  ? typingMessage
                  : message.content
              }}
            </p>
          </div>
          <img
            v-if="message.sender === 'user'"
            :src="userInfo.avatar"
            class="message-avatar"
            alt="用户头像"
          />
        </div>
      </div>
      <div class="chat-input">
        <input
          type="text"
          v-model="inputMessage"
          placeholder="输入消息..."
          @keyup.enter="sendMessage"
          :disabled="isLoading"
        />
        <button
          @click="sendMessage"
          :disabled="isLoading"
          :class="{ loading: isLoading }"
        >
          <span v-if="!isLoading">发送</span>
          <span v-else class="loading-dots">发送中</span>
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.chat-container {
  display: flex;
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  max-width: 100vw;
  background-color: #fff;
  overflow: hidden;
}

.chat-list {
  position: relative;
  width: 15%;
  min-width: 200px;
  border-right: 1px solid #e0e0e0;
  background-color: #f5f5f5;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
}

.chat-list-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.chat-list-content::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Opera */
}
.chat-list.collapsed {
  width: 40px;
  min-width: 40px;
}

.chat-list.collapsed .chat-item {
  display: none;
}

.collapse-button {
  position: absolute;
  right: -12px;
  top: 20px;
  width: 24px;
  height: 24px;
  background-color: #1976d2;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 1;
  font-weight: bold;
}

.collapse-button:hover {
  background-color: #1565c0;
}

.chat-item {
  padding: 15px;
  margin: 10px 0;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.2s ease;
}

.chat-item.new-chat {
  background-color: #e8f5e9;
  border: 2px dashed #4caf50;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 15px;
}

.chat-item.new-chat h3 {
  margin: 0;
  font-size: 16px;
  color: #4caf50;
  display: flex;
  align-items: center;
  height: 100%;
  width: 100%;
}

.chat-item.new-chat h3::before {
  content: "+";
  font-size: 20px;
  color: #4caf50;
  margin-right: 8px;
  display: flex;
  align-items: center;
}

.chat-item.new-chat p {
  margin: 8px 0 0;
  font-size: 14px;
  color: #4caf50;
  padding-left: 28px;
}

.chat-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.chat-item.active {
  background-color: #e3f2fd;
  border-left: 4px solid #1976d2;
}

.chat-item h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.chat-item p {
  margin: 5px 0 0;
  font-size: 14px;
  color: #666;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.chat-input {
  display: flex;
  padding: 20px;
  border-top: 1px solid #e0e0e0;
  background-color: #fff;
}

.chat-input input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-right: 10px;
}

.chat-input button {
  padding: 10px 20px;
  background-color: #1976d2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.chat-input button:hover {
  background-color: #1565c0;
}

.user-info {
  padding: 15px;
  background-color: white;
  border-top: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.user-details {
  flex: 1;
  min-width: 0;
}

.user-details h3 {
  margin: 0;
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.user-details p {
  margin: 2px 0 0;
  font-size: 12px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-list.collapsed .user-info {
  display: none;
}
</style>

<style scoped>
.message {
  margin: 10px 0;
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
}

.message.user {
  justify-content: flex-end;
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 12px;
  position: relative;
}

.user .message-content {
  background-color: #1976d2;
  color: white;
}

.assistant .message-content {
  background-color: #f5f5f5;
  color: #333;
}

.message-content p {
  margin: 0;
  white-space: pre-wrap;
}

.timestamp {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
  display: block;
}

.user .timestamp {
  color: rgba(255, 255, 255, 0.7);
}
.chat-input button.loading {
  position: relative;
  background-color: #1976d2;
  opacity: 0.8;
  cursor: not-allowed;
}

.loading-dots::after {
  content: "";
  animation: dots 1.5s infinite;
}

@keyframes dots {
  0% {
    content: "";
  }
  25% {
    content: ".";
  }
  50% {
    content: "..";
  }
  75% {
    content: "...";
  }
  100% {
    content: "";
  }
}
.chat-header {
  padding: 15px 20px;
  border-bottom: 1px solid #e0e0e0;
  background-color: #fff;
}

.chat-header h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
  font-weight: 500;
}

.scroll-bottom-button {
  position: absolute;
  right: 20px;
  bottom: 80px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #1976d2;
  color: white;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
}

.scroll-bottom-button:hover {
  background-color: #1565c0;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

.chat-main {
  position: relative;
}
</style>
